const Koa = require('koa')
const jwtKoa = require('koa-jwt')
const cors = require('koa-cors') // 设置请求头部
const bodyParser = require('koa-bodyparser')
const jwt = require('jsonwebtoken')
const app = new Koa()
const secret = 'martinCai'
const router = require('./router/main')
const qiniu = require('./router/qiniu')
const getInfo = require('./router/getInfo')
const zhihu = require('./router/zhihu')
const movie = require('./router/movie')
const smile = require('./router/smile')
const writeArticle = require('./router/writeArticle')

app.use(bodyParser())

app.use(cors({
  origin: function (ctx) {
    if (ctx.url === '/test') {
      return false;
    }
    return '*';
  },
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 5,
  credentials: true,
  allowMethods: ['GET', 'POST', 'DELETE'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

app.use(async (ctx, next) => {
  try {
    // 获取jwt
    const token = ctx.request.headers.authorization;
    if (token) {
      try {
        // 解密payload，获取用户名和ID
        let payload = await jwt.verify(token.split(' ')[1], secret)
        ctx.user = {
          name: payload.name
        }
      } catch (err) {
        console.log('token verify fail: ', err)
      }
    }
    await next()
  } catch (err) {
    if (err.status === 401) {
      ctx.status = 401
      ctx.body = {
        code: 401,
        success: 0,
        message: '认证失败'
      };
    } else if (err.status === 200) {
      await next()
    }
  }
  // return next().then(async () => {
  //   const token = ctx.request.headers.authorization
  //   var decoded = await jwt.verify(token.split(' ')[1], 'martinCai')
  //   ctx.user = {
  //     name: decoded.name
  //   }
  // }).catch((err) => { // 错误拦截
  //   if (err.status === 401) {
  //     ctx.status = 401
  //     ctx.body = {
  //       code: 401,
  //       response: 'token失效',
  //       msg: err.originalError ? err.originalError.message : err.message
  //     }
  //   } else {
  //       throw err
  //   }
  // })
})

app.use(jwtKoa({ secret }).unless({
  path: [/\/login/, /\/register/, /\/modeify\/password/, /\/movie\/list/, /\/smile\/list/, /\/zhihu\/hot\/list/, /\/zhihu\/hot\/detail/] //数组中的路径不需要通过jwt验证
}))

app.use(router.routes()).use(router.allowedMethods())
app.use(qiniu.routes()).use(qiniu.allowedMethods())
app.use(getInfo.routes()).use(getInfo.allowedMethods())
app.use(zhihu.routes()).use(zhihu.allowedMethods())
app.use(movie.routes()).use(movie.allowedMethods())
app.use(smile.routes()).use(smile.allowedMethods())
app.use(writeArticle.routes()).use(writeArticle.allowedMethods())

app.listen(3001)